package chp10.home;

import java.util.Random;
import java.util.Scanner;

public class GuessNum {
    public static void main(String[] args) {
// 生成1到100之间的随机整数
        Random random = new Random();
        int targetNumber = random.nextInt(100) + 1;
        int maxAttempts = 10; // 最大尝试次数
        int attempts = 0; // 当前尝试次数
        Scanner scanner = new Scanner(System.in);

        System.out.println("猜测一个1到100之间的数字:");

        while (attempts < maxAttempts) {
            System.out.print("请输入你的猜测: ");
            String input = scanner.nextLine();

            int guess;
            try {
                guess = Integer.parseInt(input);
            } catch (NumberFormatException e) {
                System.out.println("请输入一个有效的整数。");
                continue;
            }

            attempts++;

            if (guess < 1 || guess > 100) {
                System.out.println("请输入1到100之间的数字。");
                continue;
            }

            if (guess == targetNumber) {
                System.out.println("恭喜你，猜中了! 你总共猜了 " + attempts + " 次。");
                break;
            } else if (guess < targetNumber) {
                System.out.println("猜小了，再试试看。");
            } else {
                System.out.println("猜大了，再试试看。");
            }

            if (attempts == maxAttempts) {
                System.out.println("很遗憾，你已经用完了所有尝试机会。正确答案是: " + targetNumber);
            }
        }

        scanner.close();
    }
}
